package org.example.sword2offer.primary;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @version 1.0.0
 * @author: lynn
 * @description:
 * @date: 2021/8/12 23:36
 */

//fixme https://www.bilibili.com/video/BV1E741157Lj?p=10
public class Q91_MyThreadPoolExcutor {
    //一直在保持运行的线程
    private List<WorkThread> workThreads;

    //执行我们的任务队列容器
    private BlockingQueue<Runnable> taskRunnables;

    public Q91_MyThreadPoolExcutor(int workThreads,int taskRunnables){
        this.taskRunnables=new LinkedBlockingQueue<Runnable>(taskRunnables);
        //1.提前预热创建固定的线程，一直保持在运行的状态，构造函数代码中
        this.workThreads=new ArrayList<WorkThread>();
        for(int i=0;i<workThreads;i++){
            WorkThread workThread=new WorkThread();
            workThread.start();
            this.workThreads.add(workThread);
        }
    }
    public boolean execute(Runnable runnable){
        //2.当我们在调用execute的方法的时候，将任务类存入到队列中
        return taskRunnables.offer(runnable);
    }
    class WorkThread extends Thread{
        @Override
        public void run() {
            while(true){
                Runnable task=taskRunnables.poll();
                if (task!=null) task.run();
            }
        }
    }


    public static void main(String[] args) {
        Q91_MyThreadPoolExcutor myThreadPoolExcutor=new Q91_MyThreadPoolExcutor(3,3);
        for (int i = 0; i <10 ; i++) {
            final int li=i;
            myThreadPoolExcutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"task start ."+li);
                }
            });
        }

    }
}
